import logging

from rest_framework import viewsets
from drf_yasg.utils import swagger_auto_schema
from django.db import transaction

from api.v1.account.repository.serializers import *
from api.v1.account.repository.provider_account import *
from common.utils import json_response, param_info
from common import exceptions
from conf.parameters import *
from db.models import *

LOG = logging.getLogger(__name__)


class UserViewSet(viewsets.ViewSet):
    def __init__(self):
        super(UserViewSet, self).__init__()
        self.logger = LOG
        self.AccountUserProvider = AccountUserProvider()

    @swagger_auto_schema(operation_description="获取用户列表")
    @param_info
    def list(self, request):
        try:
            request.method = "GET"
            user_obj = AxeUserInfo.objects.all()
            user_list = [u.__dict__ for u in user_obj]
            return json_response(data=user_list, message="查询成功", paging=False)
        except Exception as ex:
            return json_response(message=str(ex), success=False, user_info="用户信息查询失败！！")

    @swagger_auto_schema(request_body=RegisterSerializer, operation_description="创建用户")
    @param_info
    def create(self, request):
        try:
            request.method = "POST"
            # 查询用户邮箱是否已存在
            account_mail = request.data.get("account")
            obj = AxeUserInfo.objects.filter(account=account_mail, status__in=STATUS).first()
            if obj:
                message = {"user_info": "{account}has been registered, please change your email to register!".format(
                    account=account_mail)}
                raise exceptions.CoustomException(message=message)

            # 用户创建
            with transaction.atomic():
                self.logger.info("create user body:%s " % request.data)
                user_create_obj = self.AccountUserProvider.register_provider(param_info=request.data)
            return json_response(data=user_create_obj, message="创建成功", paging=False)
        except Exception as ex:
            return json_response(message=str(ex), success=False, user_info="用户创建失败！！")

    @swagger_auto_schema(request_body=RegisterSerializer, operation_description="删除用户")
    @param_info
    def destroy(self, request):
        request.method = "POST"
        return json_response(data=[], message="删除成功", paging=False)


class UserViewDetailSet(viewsets.ViewSet):
    def __init__(self):
        super(UserViewDetailSet, self).__init__()
        self.logger = LOG

    @swagger_auto_schema(operation_description="查询用户信息")
    @param_info
    def detail(self, request):
        request.method = "GET"
        return json_response(data=[], message="删除成功", paging=False)

    @swagger_auto_schema(request_body=RegisterSerializer, operation_description="更新用户信息")
    @param_info
    def update(self, request):
        request.method = "POST"
        return json_response(data=[], message="更新成功", paging=False)
